/**
 * @projectName gs_online
 * @package com.answer.wx.service.impl
 * @className com.answer.wx.service.impl.UserServiceImpl
 */
package com.answer.wx.gateway.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSON;
import com.answer.wx.common.enums.ErrorEnum;
import com.answer.wx.common.exception.RequestException;
import com.answer.wx.dao.mapper.UserMapper;
import com.answer.wx.dao.model.User;
import com.answer.wx.gateway.config.filter.RequestInfoHolder;
import com.answer.wx.gateway.config.wx.WxMaConfiguration;
import com.answer.wx.gateway.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Optional;

/**
 * UserServiceImpl
 * @description User服务实现类
 * @author answer_wx
 * @date 2022/8/5 23:24
 * @version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int save(User user) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("userOpenid", user.getUserOpenid());
        User sqlUser = userMapper.selectByExample(example).stream().findFirst().orElse(null);
        if (sqlUser == null) {
            userMapper.insertSelective(user);
            return user.getUserId();
        } else {
            user.setUserId(sqlUser.getUserId());
            userMapper.updateByPrimaryKeySelective(user);
        }
        return sqlUser.getUserId();
    }

    @Override
    public User getById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public void info(String appid, String sessionKey, String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            throw new RequestException(ErrorEnum.OPERATION_FAIL, "校验用户信息失败");
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        User user = new User();
        user.setUserOpenid(RequestInfoHolder.getOpenId());
        user.setUserAvatar(userInfo.getAvatarUrl());
        user.setUserNickname(userInfo.getNickName());
        user.setUserOpenid(userInfo.getOpenId());
        user.setUserGender("男".equals(userInfo.getGender()) ? 1 : "女".equals(userInfo.getGender()) ? 2 : 0);
        save(user);
    }
}